import { createBaseApi, useListApi, useInfoApi } from './baseApi';
import { extend, ResponseError } from 'umi-request';
import { useCallback } from 'react';
import { IList, IBlog, IUser, IProject, IComment, IFriend } from '../interface';
import { useSnackbar } from 'notistack';
import { errorHandler } from '../utils/request';

function useErrorHandler() {
  const snackbar = useSnackbar();
  return useCallback((error: ResponseError) => {
    errorHandler(error, snackbar);
  }, []);
}

export function useUserApi() {
  const errorHandler = useErrorHandler();
  const api = createBaseApi({
    pathName: '/miao/user',
    errorHandler,
  });
  return {
    info: () => api.request<IUser>(api.pathName),
  };
}

export function useProjectApi() {
  const errorHandler = useErrorHandler();
  const api = createBaseApi({
    pathName: '/miao/project',
    errorHandler,
  });
  return {
    list: useListApi<IProject>(api),
    info: useInfoApi<IProject>(api),
  };
}

export function useFriendApi() {
  const errorHandler = useErrorHandler();
  const api = createBaseApi({
    pathName: '/miao/friend',
    errorHandler,
  });
  return {
    list: useListApi<IFriend>(api),
    info: useInfoApi<IFriend>(api),
  };
}

export function useBlogApi() {
  const errorHandler = useErrorHandler();
  const api = createBaseApi({
    pathName: '/miao/article',
    errorHandler,
  });
  return {
    list: useListApi<IBlog>(api),
    info: useInfoApi<IBlog>(api),
    commentList: (blogId: number | string) =>
      api.request<IList<IComment>>(`/miao/article/${blogId}/comment/list`),
    addComment: (blogId: number | string, commentData: any) =>
      api.request.post<IComment>(`/miao/article/${blogId}/comment`, {
        requestType: 'json',
        data: commentData,
      }),
  };
}
